#ifndef THREAD_H
#define THREAD_H
#include <iostream>
#include <string>
#include <pthread.h>
#include <cstdio>
#include <cstring>
#include <functional>
#include<unistd.h>
#include<vector>
using namespace std;

namespace td
{
    static uint32_t num=1; 
    template <class T>
    class Thread
    {
        using func_t = function<void(T)>;
    public:
        Thread(func_t func, T data) : _tid(0), _res(nullptr),
                                      _func(func), _isrunning(false),
                                      _isdetach(false),_data(data)
        {
        _name="Thread-"+to_string(num++);
       
        }
           static void *Routine(void *arg){
               Thread *self =static_cast<Thread*>(arg);
                   //需要查看是否进行了start前的detach操作：
                 self->_isrunning=1;
                   if(self->_isdetach) pthread_detach(self->_tid);
                   self->_func(self->_data);
                   return nullptr;
             
           }
         bool start(){
            if(_isrunning) return false;
            int n = pthread_create(&_tid, nullptr, Routine, this);
            if (n != 0)
            {
                cerr << "create thread error: " << strerror(n) << endl;
                return false;
            }
            else
            {
                cout << _name << " create success" << endl;
                return true;
            }
         }
         bool stop(){
             if(_isrunning){
             int n= pthread_cancel(_tid);
               if (n != 0)
               {
                   cerr << "cancel thread error: " << strerror(n) << endl;
                   return false;
               }
               else
               {
                   _isrunning = false;
                   cout << _name << " stop" << endl;
                   return true;
               }

             }
             return false;
         }
         bool detach(){
            if(_isdetach) return false;
            if(_isrunning)pthread_detach(_tid);//创建成功的线程进行分离操作
            _isdetach=1;//未创线程进行分离只进行标记
            return true;
         }
         bool join(){
           if(_isdetach) {
            cout<<"线程 "<<_name<<"已经被分离;不能进行join"<<endl;
            return false;
           }
           //只考虑运行起来的线程了：
           int n = pthread_join(_tid, &_res);
           if (n != 0)
           {
               std::cerr << "join thread error: " << strerror(n) << std::endl;
           }
           else
           {
               std::cout << "join success" << std::endl;
           }

          return true;
         }
     
        ~Thread() {}

    private:
        pthread_t _tid;
        string _name;
        void *_res;
        func_t _func;
        T _data;
        bool _isrunning;
        bool _isdetach;
    };
}

#endif